﻿using DataAchive.Common;
using DataAchive.Extend;
using DataAchive.Helper;
using DataAchive.Model.Excel.Export;
using DataAchive.Model.Excel.Export.Fanxiu;
using MySql.Data.MySqlClient;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Asn1.X509;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace DataAchive
{
    /// <summary>
    /// ReportShow.xaml 的交互逻辑
    /// </summary>
    public partial class ReportShow : Window
    {
        public ReportShow()
        {
            InitializeComponent();

            ConnectionHelper.GetXmlSetting();
            ConnectionHelper.GetXmlMachineSetting();

            if (ConnectionHelper.siteAndConnections.Count == 0)
            {
                connectionState.Text = "未读取到配置文件有效的ip地址设置！！";
                connectionState.Foreground= Brushes.Red;
                return;
            }
            AddressCombo.ItemsSource = ConnectionHelper.siteAndConnections;
            AddressCombo.DisplayMemberPath = "Key";
            AddressCombo.SelectedValuePath = "Value";


            #region btn

            reportArea.IsEnabled = false;
            #endregion
        }

        private void connectBtn_Click(object sender, RoutedEventArgs e)
        {
            var address = AddressCombo.SelectedValue?.ToString();
            var site =AddressCombo.SelectedItem?.ToString();            

            if (String.IsNullOrWhiteSpace(address))
            {
                MessageBox.Show("请选择集控室(请提前配置好集控室信息.)！");
                return;
            }
            List<string> equips = null;
            try
            {
                // equips = GetEquipments(address, AddressCombo.SelectedItem?.ToString());

                var typs = ConnectionHelper.siteAndMachineids.Select(x => x.Key)?.ToList() ?? new List<string>();               
                TypeCombo.ItemsSource = typs;

                if (typs.Count > 0)
                {
                    TypeCombo.SelectedIndex = 0;
                }
                

            }
            catch (Exception exx)
            {
                MessageBox.Show("连接失败!");

                #region btn
                reportArea.IsEnabled = false;
                connectionState.Text= exx.Message;
                #endregion
                
                return;
            }

            #region btn
            reportArea.IsEnabled = true;
            connectBtn.IsEnabled = false;
            #endregion


            //if (equips == null || equips.Count == 0)
            //{
            //    connectionState.Text = $"{site}的设备读取为空。请确认连接是否正常、该站点是否有数据。";
            //    return;
            //}
         

            connectionState.Text = $"{site}的设备读取成功！";
           // EquipmentCombo.ItemsSource= equips;
          
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataset"></param>
        /// <returns>List<string> 列值列表</returns>
        static List<string> GetEquipments(string address,string site)
        {
            using (MySqlConnection connection = new MySqlConnection(address))
            {
                try
                {
                    MySqlCommand cmd = new MySqlCommand();
                    if (connection.State != ConnectionState.Open)
                        connection.Open();
                    cmd.Connection = connection;
                    cmd.CommandText = "SELECT  equipment_id FROM site GROUP BY equipment_id  ";

                    cmd.Connection = connection;

                    using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
                    {
                        DataSet ds = new DataSet();
                        try
                        {
                            da.Fill(ds, "ds");
                            cmd.Parameters.Clear();

                            // 调用方法提取列值并保存为 List<string>
                            List<string> equipmentIds = ExtractEquipmentIds(ds);
                            return equipmentIds;


                        }
                        catch (Exception ex)
                        {
                            SoftCommon.Log.Write($"SQL异常：{ex.Message}");
                            MessageBox.Show("连接异常,请检查！");

                            return null;
                        }

                    }
                }
                catch (Exception e)
                {
                    SoftCommon.Log.Write("连接异常："+e.Message);
                    
                    throw e;
                }
             
            }           

           
        }

        static List<string> ExtractEquipmentIds(DataSet dataset)
        {         

            List<string> equipmentIds = new List<string>();

            // 确保 DataSet 中只有一个 DataTable
            if (dataset.Tables.Count != 1)
            {
                throw new InvalidOperationException("DataSet 中必须且只能有一个 DataTable。");
            }

            // 获取唯一的 DataTable
            DataTable table = dataset.Tables[0];

            // 检查 DataTable 是否为空或无列，如果是则抛出异常
            if (table == null || table.Columns.Count == 0)
            {
                throw new InvalidOperationException("DataTable 必须包含至少一列。");
            }

            // 获取指定列的名称（假设列名为 "equipment_id"）
            string columnName = "equipment_id";

            // 检查列是否存在
            if (!table.Columns.Contains(columnName))
            {
                throw new InvalidOperationException($"DataTable 中不存在列 '{columnName}'。");
            }

            // 遍历 DataTable 的行，并提取指定列的值
            foreach (DataRow row in table.Rows)
            {
                if (row[columnName] != DBNull.Value && !string.IsNullOrWhiteSpace(row[columnName]?.ToString()))
                {
                    equipmentIds.Add(row[columnName].ToString());
                }
            }

            return equipmentIds;
        }

        private void AddressCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var addresscombo = sender as ComboBox;
            if (addresscombo != null) { 
            
            }
            #region btn
          
            connectBtn.IsEnabled = true;
            connectionState.Text= string.Empty;
            reportArea.IsEnabled = false;
           
            #endregion


        }

        private void detailReportBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region btn
                detailReportBtn.IsEnabled = false;
                #endregion

                SoftCommon.Log.Write($"导出按钮点击");
                string path = string.Empty;
                // 创建 FolderBrowserDialog 对话框实例
                using (System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    // 显示对话框，并等待用户选择文件夹
                    System.Windows.Forms.DialogResult result = folderDialog.ShowDialog();

                    // 如果用户点击了确定按钮，获取选定的文件夹路径并显示在界面上
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        path = folderDialog.SelectedPath;
                    }
                }
                SoftCommon.Log.Write($"用户选择文件保存地址：{path}");
                if (string.IsNullOrWhiteSpace(path))
                {
                    #region btn
                    detailReportBtn.IsEnabled = true;

                    #endregion
                    return;
                }

                WhereQ whereQ = new WhereQ();
                //whereQ.Date = reportDate.SelectedDate??DateTime.MinValue;
                whereQ.BeginTime = beginDate.TimeValue;
                whereQ.EndTime = endDate.TimeValue;
              //  whereQ.EquitepmentId = EquipmentCombo.SelectedValue?.ToString();
                var selectEquips = EquipmentCombo.SelectedItems.Cast<string>().ToList();
                whereQ.ManyEquitepmentIds = selectEquips;

                string address = AddressCombo.SelectedValue?.ToString();
                string typeExport = exportType.SelectedValue?.ToString();


                var dstail = ReportHelper.GetDetailReportInfo(whereQ, address);
                var dtval = ReportHelper.DetailReportTrans(dstail.Tables[0]);
                var lsresult = ReportHelper.DicToList(dtval);

                string addSettingAddress = string.Empty;
                if (AddressCombo.SelectedItem is KeyValuePair<string, string> kvp)
                {
                    // 是 key-value 对象
                    addSettingAddress = kvp.Key;

                }
                else
                {
                    addSettingAddress = AddressCombo.SelectedItem?.ToString()?.Split(',')[0];
                }
                if (typeExport.Equals("CSV", StringComparison.OrdinalIgnoreCase))
                {
                    string fileName = $@"{path}\{addSettingAddress}详情报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
                    ReportExport<DetailReport>.ExportCsv(lsresult, fileName);
                    MessageBox.Show("导出结束");
                }
                else
                {
                    string fileName = $@"{path}\{addSettingAddress}详情报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
                    ReportExport<DetailReport>.ExportXsls(lsresult, fileName);
                    MessageBox.Show("导出结束");
                }
                

            }
            catch (Exception ed)
            {
                SoftCommon.Log.Write("导出异常："+ed.Message);
                MessageBox.Show("导出异常！！");
         
            }
            #region btn
            detailReportBtn.IsEnabled = true;
           
            #endregion
        }

        private void allNgReportBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region btn
                allNgReportBtn.IsEnabled = false;
                #endregion

                SoftCommon.Log.Write($"NG导出按钮点击");
                string path = string.Empty;
                // 创建 FolderBrowserDialog 对话框实例
                using (System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    // 显示对话框，并等待用户选择文件夹
                    System.Windows.Forms.DialogResult result = folderDialog.ShowDialog();

                    // 如果用户点击了确定按钮，获取选定的文件夹路径并显示在界面上
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        path = folderDialog.SelectedPath;
                    }
                }
                SoftCommon.Log.Write($"用户选择文件保存地址：{path}");
                if (string.IsNullOrWhiteSpace(path))
                {
                    #region btn
                    allNgReportBtn.IsEnabled = true;

                    #endregion
                    return;
                }

                WhereQ whereQ = new WhereQ();
                //whereQ.Date = reportDate.SelectedDate??DateTime.MinValue;
                whereQ.BeginTime = beginDate.TimeValue;
                whereQ.EndTime = endDate.TimeValue;
                //  whereQ.EquitepmentId = EquipmentCombo.SelectedValue?.ToString();
                var selectEquips = EquipmentCombo.SelectedItems.Cast<string>().ToList();
                whereQ.ManyEquitepmentIds = selectEquips;

                string address = AddressCombo.SelectedValue?.ToString();
                string typeExport = exportType.SelectedValue?.ToString();


                var dstailSet = ReportHelper.GetDetailReportInfo(whereQ, address);
              
                var lsresult = ReportHelper.AllNginfoToList(dstailSet);
                string addSettingAddress = string.Empty;
                if (AddressCombo.SelectedItem is KeyValuePair<string, string> kvp)
                {
                    // 是 key-value 对象
                    addSettingAddress = kvp.Key;

                }
                else
                {
                    addSettingAddress = AddressCombo.SelectedItem?.ToString()?.Split(',')[0];
                }

                if (typeExport.Equals("CSV", StringComparison.OrdinalIgnoreCase))
                {
                    string fileName = $@"{path}\{addSettingAddress}所有信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
                    ReportExport<AllNGInfoRepChange>.ExportCsv(lsresult, fileName);
                    MessageBox.Show("导出结束");
                }
                else
                {
                    string fileName = $@"{path}\{addSettingAddress}所有信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
                    ReportExport<AllNGInfoRepChange>.ExportXsls(lsresult, fileName);
                    MessageBox.Show("导出结束");
                }


            }
            catch (Exception ed)
            {
                SoftCommon.Log.Write("导出异常：" + ed.Message);
                MessageBox.Show("导出异常！！");

            }
            #region btn
            allNgReportBtn.IsEnabled = true;

            #endregion
        }

        private void colRowReportBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region btn
                colRowReportBtn.IsEnabled = false;
                #endregion

                SoftCommon.Log.Write($"colRowReportBtn_Click");
                string path = string.Empty;
                // 创建 FolderBrowserDialog 对话框实例
                using (System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    // 显示对话框，并等待用户选择文件夹
                    System.Windows.Forms.DialogResult result = folderDialog.ShowDialog();

                    // 如果用户点击了确定按钮，获取选定的文件夹路径并显示在界面上
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        path = folderDialog.SelectedPath;
                    }
                }
                SoftCommon.Log.Write($"用户选择文件保存地址：{path}");
                if (string.IsNullOrWhiteSpace(path))
                {
                    #region btn
                    colRowReportBtn.IsEnabled = true;

                    #endregion
                    return;
                }

                WhereQ whereQ = new WhereQ();
                //whereQ.Date = reportDate.SelectedDate??DateTime.MinValue;
                whereQ.BeginTime = beginDate.TimeValue;
                whereQ.EndTime = endDate.TimeValue;
                // whereQ.EquitepmentId = EquipmentCombo.SelectedValue?.ToString();
                var selectEquips = EquipmentCombo.SelectedItems.Cast<string>().ToList();
                whereQ.ManyEquitepmentIds = selectEquips;

                string address = AddressCombo.SelectedValue?.ToString();
                string typeExport = exportType.SelectedValue?.ToString();

                //finishtime -- judge
                var dstail = ReportHelper.GetColRowReportInfo(whereQ, address);
                var dtval = ReportHelper.DetailReportTrans(dstail.Tables[0]);
                var lsresult = ReportHelper.DicColRowToList(dtval);
                lsresult.ForEach(x =>
                {
                    // var min = FindMinTime(x.ElCreateTime,x.VICreateTime,x.VBCreateTime);
                    var min_max = FindMaxTime(x.ElCreateTime, x.VICreateTime, x.VBCreateTime);
                    var max = FindMaxTime(x.ElFinishTime, x.VIFinishTime, x.VBFinishTime);
                    if (min_max == DateTime.MinValue || max == DateTime.MinValue)
                    {
                       
                    }
                    else
                    {
                        x.HumanJudgeTime =max- min_max;
                    }
                    var direc = isDirectRes(x.ElAiDetectResult,x.VIAiDetectResult,x.VBAiDetectResult);
                    x.IsDirect = direc?"是":"否";
                    if (direc)
                    {
                        x.HumanJudgeTime = TimeSpan.Zero;
                    }
                    int aiR = noNullResult(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    int RenR = noNullResult(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult);
                    if(aiR== RenR)
                    {
                        if (aiR == 1)
                        {
                            x.LouJianOrGuopan = louWu(
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0]
                                );
                        }
                        else if (aiR == 2)
                        {
                            x.LouJianOrGuopan = louWu(
                              noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                              noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1]
                              );
                        }
                        else if (aiR == 3)
                        {
                            x.LouJianOrGuopan = louWu(
                              noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                                 noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[2],
                              noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1],
                                   noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[2]
                              );
                        }
                    }

                    List<string>aielInfoList = new List<string>();
                   
                    if (!string.IsNullOrWhiteSpace(x.ElAiDetectInfo))
                    {
                        string[] allQx = x.ElAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu= item.Split(':');
                            if (shuzu.Length ==2)
                            {
                                aielInfoList.Add(shuzu[1]);
                            }
                            else if(shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aielInfoList.Add(shuzu[1]);
                            }                         
                        }
                    }
                    aielInfoList = aielInfoList.Distinct().ToList();
                    aielInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ElAiDetectInfo = string.Join(",", aielInfoList);

                    List<string> aiviInfoList = new List<string>();
                    
                    if (!string.IsNullOrWhiteSpace(x.ViAiDetectInfo))
                    {
                        string[] allQx = x.ViAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aiviInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aiviInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aiviInfoList = aiviInfoList.Distinct().ToList();
                    aiviInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ViAiDetectInfo = string.Join(",", aiviInfoList);

                    List<string> aivbInfoList = new List<string>();
                    
                    if (!string.IsNullOrWhiteSpace(x.VBAiDetectInfo))
                    {
                        string[] allQx = x.VBAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aivbInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aivbInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aivbInfoList = aivbInfoList.Distinct().ToList();
                    aivbInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.VBAiDetectInfo = string.Join(",", aivbInfoList);

                });

                lsresult.ForEach(x => { 
                    if(x.HumanJudgeTime!= TimeSpan.Zero&&string.IsNullOrWhiteSpace(x.LouJianOrGuopan))
                    {
                        x.LouJianOrGuopan = "NG";
                    }
                
                });
                string addSettingAddress = string.Empty;
                if (AddressCombo.SelectedItem is KeyValuePair<string, string> kvp)
                {
                    // 是 key-value 对象
                    addSettingAddress = kvp.Key;

                }
                else
                {
                    addSettingAddress = AddressCombo.SelectedItem?.ToString()?.Split(',')[0];
                }
                if (typeExport.Equals("CSV", StringComparison.OrdinalIgnoreCase))
                {
                    string fileName = $@"{path}\{addSettingAddress}合并信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
                    ReportExport<ColRowReport>.ExportCsv(lsresult, fileName);
                    MessageBox.Show("导出结束");
                }
                else
                {
                    string fileName = $@"{path}\{addSettingAddress}合并信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
                    ReportExport<ColRowReport>.ExportXsls(lsresult, fileName);
                    MessageBox.Show("导出结束");
                }
              
            }
            catch (Exception ed)
            {
                SoftCommon.Log.Write("导出异常：" + ed.Message);
                MessageBox.Show("导出异常！！");

            }
            #region btn
            colRowReportBtn.IsEnabled = true;

            #endregion
        }

      public static  DateTime FindMinTime(DateTime t1, DateTime t2, DateTime t3)
        {
            return new DateTime[] { t1, t2, t3 }.Where(t => t != DateTime.MinValue).Min();
        }
        public static DateTime FindMaxTime(DateTime t1, DateTime t2, DateTime t3)
        {
            return new DateTime[] { t1, t2, t3 }.Max();
        }
        public static bool isDirectRes(string t1, string t2, string t3)
        {
            var li = new string[] { t1, t2, t3 }.Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
            var b = li.Where(x => x.Equals("OK", StringComparison.OrdinalIgnoreCase)).Count() == li.Count();
            return b;
        }
        public static int noNullResult(string t1, string t2, string t3)
        {
            return new string[] { t1, t2, t3 }.Where(x => !string.IsNullOrWhiteSpace(x)).Count();
        }
        public static List<string> noNullVal(string t1, string t2, string t3)
        {
            return new string[] { t1, t2, t3 }.Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
        }
        public static string louWu(string ta, string tr)
        {

            if (ta.Equals("NG", StringComparison.OrdinalIgnoreCase) && tr.Equals("OK", StringComparison.OrdinalIgnoreCase))
            {
                return "过判";
            }
            else
            {
                return "";
            }
            //return "漏检/过判";
        }
        public static string louWu(string ta, string ta2, string tr, string tr2)
        {

            if ((ta.Equals("NG", StringComparison.OrdinalIgnoreCase) && tr.Equals("OK", StringComparison.OrdinalIgnoreCase)) ||
                (ta2.Equals("NG", StringComparison.OrdinalIgnoreCase) && tr2.Equals("OK", StringComparison.OrdinalIgnoreCase)))
            {
                return "过判";
            }
            else
            {
                return "";
            }
        }

        public static string louWu(string ta, string ta2, string ta3, string tr, string tr2, string tr3)
        {

            if ((ta.Equals("NG", StringComparison.OrdinalIgnoreCase) && tr.Equals("OK", StringComparison.OrdinalIgnoreCase)) ||
                (ta2.Equals("NG", StringComparison.OrdinalIgnoreCase) && tr2.Equals("OK", StringComparison.OrdinalIgnoreCase)) ||
                (ta3.Equals("NG", StringComparison.OrdinalIgnoreCase) && tr3.Equals("OK", StringComparison.OrdinalIgnoreCase)))
            {
                return "过判";
            }
            else
            {
                return "";
            }
        }

        private void TypeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var typeName =TypeCombo.SelectedItem?.ToString();
            if (!String.IsNullOrWhiteSpace(typeName))
            {
               var listMach = ConnectionHelper.siteAndMachineids[typeName];
                if (listMach != null)
                {
                    EquipmentCombo.ItemsSource = listMach;
                }
                else
                {
                    EquipmentCombo.ItemsSource = new List<string>();
                }
              
            }
           
        }

        private void dayReportBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region btn
                dayReportBtn.IsEnabled = false;
                #endregion

                SoftCommon.Log.Write($"dayReportBtn click");
                string path = string.Empty;
                // 创建 FolderBrowserDialog 对话框实例
                using (System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    // 显示对话框，并等待用户选择文件夹
                    System.Windows.Forms.DialogResult result = folderDialog.ShowDialog();

                    // 如果用户点击了确定按钮，获取选定的文件夹路径并显示在界面上
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        path = folderDialog.SelectedPath;
                    }
                }
                SoftCommon.Log.Write($"dayReportBtn save address ：{path}");
                if (string.IsNullOrWhiteSpace(path))
                {
                    #region btn
                    dayReportBtn.IsEnabled = true;

                    #endregion
                    return;
                }

                WhereQ whereQ = new WhereQ();

                whereQ.BeginTime = beginDate.TimeValue;
                whereQ.EndTime = endDate.TimeValue;

                var selectEquips = EquipmentCombo.SelectedItems.Cast<string>().ToList();
                whereQ.ManyEquitepmentIds = selectEquips;

                string address = AddressCombo.SelectedValue?.ToString();
                string typeExport = exportType.SelectedValue?.ToString();


                var dstailSet = ReportHelper.GetDetailReportInfo(whereQ, address, ReportHelper.DetailLittleSql);

                var lsresult = ReportHelper.AllNginfoToList(dstailSet);

                Dictionary<string, HashSet<string>> aiPairs = new Dictionary<string, HashSet<string>>();
                Dictionary<string, HashSet<string>> manualPairs = new Dictionary<string, HashSet<string>>();
                Dictionary<string, bool> viewDic = new Dictionary<string, bool>();
                foreach (var item in lsresult)
                {
                    if (!aiPairs.ContainsKey(item.Lot_Id))
                    {
                        HashSet<string> aiH = new HashSet<string>() { item.AI_Result };

                        aiPairs.Add(item.Lot_Id, aiH);
                    }
                    else
                    {
                        aiPairs[item.Lot_Id].Add(item.AI_Result);
                    }

                    if (!manualPairs.ContainsKey(item.Lot_Id))
                    {
                        HashSet<string> muh = new HashSet<string>() { item.Manua_Result };

                        manualPairs.Add(item.Lot_Id, muh);
                    }
                    else
                    {
                        manualPairs[item.Lot_Id].Add(item.Manua_Result);
                    }
                }

                //按机台分组，获取检测量等
                var grpEquips = lsresult.GroupBy(x => x.Equipment_Id);
                List<SummaryReport> summaryReports = new List<SummaryReport>();

                Dictionary<string, string> kvEquip = new Dictionary<string, string>();
                foreach (var grpEq in grpEquips)
                {
                    SummaryReport summaryReport = new SummaryReport()
                    {
                        Equipment = grpEq.Key,
                        DetectNumber = grpEq.Count(),
                        // GuopanLv =0,
                        // GuopanNumber=0,
                        //  GuopanType=""
                    };
                    int guopanCount = 0;
                    foreach (var item in grpEq)
                    {
                        if (!viewDic.ContainsKey(item.Lot_Id))
                        {
                            viewDic.Add(item.Lot_Id, true);
                        }
                        else
                        {
                            continue;
                        }

                        if (aiPairs.ContainsKey(item.Lot_Id))
                        {
                            if (manualPairs.ContainsKey(item.Lot_Id))
                            {
                                var aiList = aiPairs[item.Lot_Id].Where(x => x.Equals("NG", StringComparison.OrdinalIgnoreCase)).Count();
                                //simple?
                                var manulList = manualPairs[item.Lot_Id].Where(x => x.Equals("OK", StringComparison.OrdinalIgnoreCase)).Count();
                                if (aiList > 0 && manulList > 0)
                                {
                                    SoftCommon.Log.Write(item.Lot_Id);
                                    guopanCount++;
                                }
                            }
                        }


                    }


                    summaryReport.GuopanNumber = guopanCount;
                    summaryReport.GuopanLv = Math.Round(guopanCount * 1m / grpEq.Count(), 4)*100+"%";
                    summaryReports.Add(summaryReport);
                }



                if (typeExport.Equals("CSV", StringComparison.OrdinalIgnoreCase))
                {
                    string fileName = $@"{path}\总结报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
                    ReportExport<SummaryReport>.ExportCsv(summaryReports, fileName);
                    MessageBox.Show("导出结束");
                }
                else
                {
                    string fileName = $@"{path}\总结报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
                    ReportExport<SummaryReport>.ExportXsls(summaryReports, fileName);
                    MessageBox.Show("导出结束");
                }


            }
            catch (Exception ed)
            {
                SoftCommon.Log.Write("导出异常：" + ed.Message);
                MessageBox.Show("导出异常！！");

            }
            #region btn
            dayReportBtn.IsEnabled = true;

            #endregion
        }

        private void aiDefectReportBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region btn
                aiDefectReportBtn.IsEnabled = false;
                #endregion

                SoftCommon.Log.Write($"aiDefectReportBtn_Click");
                string path = string.Empty;
                // 创建 FolderBrowserDialog 对话框实例
                using (System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    // 显示对话框，并等待用户选择文件夹
                    System.Windows.Forms.DialogResult result = folderDialog.ShowDialog();

                    // 如果用户点击了确定按钮，获取选定的文件夹路径并显示在界面上
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        path = folderDialog.SelectedPath;
                    }
                }
                SoftCommon.Log.Write($"用户选择文件保存地址：{path}");
                if (string.IsNullOrWhiteSpace(path))
                {
                    #region btn
                    aiDefectReportBtn.IsEnabled = true;

                    #endregion
                    return;
                }

                WhereQ whereQ = new WhereQ();
                //whereQ.Date = reportDate.SelectedDate??DateTime.MinValue;
                whereQ.BeginTime = beginDate.TimeValue;
                whereQ.EndTime = endDate.TimeValue;
                // whereQ.EquitepmentId = EquipmentCombo.SelectedValue?.ToString();
                var selectEquips = EquipmentCombo.SelectedItems.Cast<string>().ToList();
                whereQ.ManyEquitepmentIds = selectEquips;

                string address = AddressCombo.SelectedValue?.ToString();
                string typeExport = exportType.SelectedValue?.ToString();

                //finishtime -- judge
                var dstail = ReportHelper.GetColRowReportInfo(whereQ, address);
                var dtval = ReportHelper.DetailReportTrans(dstail.Tables[0]);
                var lsresult = ReportHelper.DicColRowToList(dtval);
                lsresult.ForEach(x =>
                {
                    // var min = FindMinTime(x.ElCreateTime,x.VICreateTime,x.VBCreateTime);
                    var min_max = FindMaxTime(x.ElCreateTime, x.VICreateTime, x.VBCreateTime);
                    var max = FindMaxTime(x.ElFinishTime, x.VIFinishTime, x.VBFinishTime);
                    if (min_max == DateTime.MinValue || max == DateTime.MinValue)
                    {

                    }
                    else
                    {
                        x.HumanJudgeTime = max - min_max;
                    }
                    var direc = isDirectRes(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    x.IsDirect = direc ? "是" : "否";
                    if (direc)
                    {
                        x.HumanJudgeTime = TimeSpan.Zero;
                    }
                    int aiR = noNullResult(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    int RenR = noNullResult(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult);
                    if (aiR == RenR)
                    {
                        if (aiR == 1)
                        {
                            x.LouJianOrGuopan = louWu(
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0]
                                );
                        }
                        else if (aiR == 2)
                        {
                            x.LouJianOrGuopan = louWu(
                              noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                              noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1]
                              );
                        }
                        else if (aiR == 3)
                        {
                            x.LouJianOrGuopan = louWu(
                              noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                                 noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[2],
                              noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1],
                                   noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[2]
                              );
                        }
                    }

                    List<string> aielInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.ElAiDetectInfo))
                    {
                        string[] allQx = x.ElAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aielInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aielInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aielInfoList = aielInfoList.Distinct().ToList();
                    aielInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ElAiDetectInfo = string.Join(",", aielInfoList);

                    List<string> aiviInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.ViAiDetectInfo))
                    {
                        string[] allQx = x.ViAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aiviInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aiviInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aiviInfoList = aiviInfoList.Distinct().ToList();
                    aiviInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ViAiDetectInfo = string.Join(",", aiviInfoList);

                    List<string> aivbInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.VBAiDetectInfo))
                    {
                        string[] allQx = x.VBAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aivbInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aivbInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aivbInfoList = aivbInfoList.Distinct().ToList();
                    aivbInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.VBAiDetectInfo = string.Join(",", aivbInfoList);

                });

                lsresult.ForEach(x => {
                    if (x.HumanJudgeTime != TimeSpan.Zero && string.IsNullOrWhiteSpace(x.LouJianOrGuopan))
                    {
                        x.LouJianOrGuopan = "NG";
                    }

                });

                // 针对 lsresult处理
               var reportDefectData = AiDefectStaticsReportAll.GetReportData(lsresult);

                if (typeExport.Equals("CSV", StringComparison.OrdinalIgnoreCase))
                {
                    string fileName = $@"{path}\缺陷汇总信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
                    ReportExport<AiDefectStaticViewModel>.ExportCsv(new List<AiDefectStaticViewModel>() { reportDefectData }, fileName);
                    MessageBox.Show("导出结束");
                }
                else
                {
                    string fileName = $@"{path}\缺陷汇总信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
                    ReportExport<AiDefectStaticViewModel>.ExportXsls(new List<AiDefectStaticViewModel>() { reportDefectData }, fileName);
                    MessageBox.Show("导出结束");
                }

            }
            catch (Exception ed)
            {
                SoftCommon.Log.Write("导出异常：" + ed.Message);
                MessageBox.Show("导出异常！！");

            }
            #region btn
            aiDefectReportBtn.IsEnabled = true;

            #endregion
        }

        //基础信息
        private void aiDefectBaseBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region btn
                aiDefectBaseBtn.IsEnabled = false;
                #endregion

                SoftCommon.Log.Write($"aiDefectBaseBtn_Click");
                string path = string.Empty;               
                // 创建 FolderBrowserDialog 对话框实例
                using (System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    // 显示对话框，并等待用户选择文件夹
                    System.Windows.Forms.DialogResult result = folderDialog.ShowDialog();

                    // 如果用户点击了确定按钮，获取选定的文件夹路径并显示在界面上
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        path = folderDialog.SelectedPath;
                    }
                }
                SoftCommon.Log.Write($"用户选择文件保存地址：{path}");
                if (string.IsNullOrWhiteSpace(path))
                {
                    #region btn
                    aiDefectBaseBtn.IsEnabled = true;

                    #endregion
                    return;
                }

                WhereQ whereQ = new WhereQ();
                //whereQ.Date = reportDate.SelectedDate??DateTime.MinValue;
                whereQ.BeginTime = beginDate.TimeValue;
                whereQ.EndTime = endDate.TimeValue;
                // whereQ.EquitepmentId = EquipmentCombo.SelectedValue?.ToString();
                var selectEquips = EquipmentCombo.SelectedItems.Cast<string>().ToList();
                whereQ.ManyEquitepmentIds = selectEquips;

                string address = AddressCombo.SelectedValue?.ToString();
                string typeExport = exportType.SelectedValue?.ToString();

                //finishtime -- judge
                var dstail = ReportHelper.GetColRowReportInfo(whereQ, address);
                var dtval = ReportHelper.DetailReportTrans(dstail.Tables[0]);
                var lsresult = ReportHelper.DicColRowToList(dtval);
                lsresult.ForEach(x =>
                {
                    // var min = FindMinTime(x.ElCreateTime,x.VICreateTime,x.VBCreateTime);
                    var min_max = FindMaxTime(x.ElCreateTime, x.VICreateTime, x.VBCreateTime);
                    var max = FindMaxTime(x.ElFinishTime, x.VIFinishTime, x.VBFinishTime);
                    if (min_max == DateTime.MinValue || max == DateTime.MinValue)
                    {

                    }
                    else
                    {
                        x.HumanJudgeTime = max - min_max;
                    }
                    var direc = isDirectRes(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    x.IsDirect = direc ? "是" : "否";
                    if (direc)
                    {
                        x.HumanJudgeTime = TimeSpan.Zero;
                    }
                    int aiR = noNullResult(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    int RenR = noNullResult(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult);
                    if (aiR == RenR)
                    {
                        if (aiR == 1)
                        {
                            x.LouJianOrGuopan = louWu(
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0]
                                );
                        }
                        else if (aiR == 2)
                        {
                            x.LouJianOrGuopan = louWu(
                              noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                              noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1]
                              );
                        }
                        else if (aiR == 3)
                        {
                            x.LouJianOrGuopan = louWu(
                              noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                                 noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[2],
                              noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1],
                                   noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[2]
                              );
                        }
                    }

                    List<string> aielInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.ElAiDetectInfo))
                    {
                        string[] allQx = x.ElAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aielInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aielInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aielInfoList = aielInfoList.Distinct().ToList();
                    aielInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ElAiDetectInfo = string.Join(",", aielInfoList);

                    List<string> aiviInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.ViAiDetectInfo))
                    {
                        string[] allQx = x.ViAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aiviInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aiviInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aiviInfoList = aiviInfoList.Distinct().ToList();
                    aiviInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ViAiDetectInfo = string.Join(",", aiviInfoList);

                    List<string> aivbInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.VBAiDetectInfo))
                    {
                        string[] allQx = x.VBAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aivbInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aivbInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aivbInfoList = aivbInfoList.Distinct().ToList();
                    aivbInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.VBAiDetectInfo = string.Join(",", aivbInfoList);

                });

                lsresult.ForEach(x => {
                    if (x.HumanJudgeTime != TimeSpan.Zero && string.IsNullOrWhiteSpace(x.LouJianOrGuopan))
                    {
                        x.LouJianOrGuopan = "NG";
                    }

                });

                // 针对 lsresult处理
                var reportDefectData = AiDefectStaticRRR.GetHReportDataAi(lsresult);

                string addSettingAddress = string.Empty;
                if (AddressCombo.SelectedItem is KeyValuePair<string, string> kvp)
                {
                    // 是 key-value 对象
                    addSettingAddress  = kvp.Key;
                    
                }
                else
                {
                    addSettingAddress = AddressCombo.SelectedItem?.ToString()?.Split(',')[0];
                }
               

                if (typeExport.Equals("CSV", StringComparison.OrdinalIgnoreCase))
                {
                    string fileName = $@"{path}\{addSettingAddress}缺陷汇总基础信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
                    ReportExport<AiDefectStaticColumnAiC>.ExportCsv(reportDefectData , fileName);
                    MessageBox.Show("导出结束");
                }
                else
                {
                    string fileName = $@"{path}\{addSettingAddress}缺陷汇总基础信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
                    ReportExport<AiDefectStaticColumnAiC>.ExportXsls(reportDefectData , fileName);
                    MessageBox.Show("导出结束");
                }

            }
            catch (Exception ed)
            {
                SoftCommon.Log.Write("导出异常：" + ed.Message);
                MessageBox.Show("导出异常！！");

            }
            #region btn
            aiDefectBaseBtn.IsEnabled = true;

            #endregion
        }

        //误检
        private void aiDefectNofoundBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region btn
                aiDefectNofoundBtn.IsEnabled = false;
                #endregion

                SoftCommon.Log.Write($"aiDefectReportBtn_Click");
                string path = string.Empty;
                // 创建 FolderBrowserDialog 对话框实例
                using (System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    // 显示对话框，并等待用户选择文件夹
                    System.Windows.Forms.DialogResult result = folderDialog.ShowDialog();

                    // 如果用户点击了确定按钮，获取选定的文件夹路径并显示在界面上
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        path = folderDialog.SelectedPath;
                    }
                }
                SoftCommon.Log.Write($"用户选择文件保存地址：{path}");
                if (string.IsNullOrWhiteSpace(path))
                {
                    #region btn
                    aiDefectNofoundBtn.IsEnabled = true;

                    #endregion
                    return;
                }

                WhereQ whereQ = new WhereQ();
                //whereQ.Date = reportDate.SelectedDate??DateTime.MinValue;
                whereQ.BeginTime = beginDate.TimeValue;
                whereQ.EndTime = endDate.TimeValue;
                // whereQ.EquitepmentId = EquipmentCombo.SelectedValue?.ToString();
                var selectEquips = EquipmentCombo.SelectedItems.Cast<string>().ToList();
                whereQ.ManyEquitepmentIds = selectEquips;

                string address = AddressCombo.SelectedValue?.ToString();
                string typeExport = exportType.SelectedValue?.ToString();

                //finishtime -- judge
                var dstail = ReportHelper.GetColRowReportInfo(whereQ, address);
                var dtval = ReportHelper.DetailReportTrans(dstail.Tables[0]);
                var lsresult = ReportHelper.DicColRowToList(dtval);
                lsresult.ForEach(x =>
                {
                    // var min = FindMinTime(x.ElCreateTime,x.VICreateTime,x.VBCreateTime);
                    var min_max = FindMaxTime(x.ElCreateTime, x.VICreateTime, x.VBCreateTime);
                    var max = FindMaxTime(x.ElFinishTime, x.VIFinishTime, x.VBFinishTime);
                    if (min_max == DateTime.MinValue || max == DateTime.MinValue)
                    {

                    }
                    else
                    {
                        x.HumanJudgeTime = max - min_max;
                    }
                    var direc = isDirectRes(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    x.IsDirect = direc ? "是" : "否";
                    if (direc)
                    {
                        x.HumanJudgeTime = TimeSpan.Zero;
                    }
                    int aiR = noNullResult(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    int RenR = noNullResult(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult);
                    if (aiR == RenR)
                    {
                        if (aiR == 1)
                        {
                            x.LouJianOrGuopan = louWu(
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0]
                                );
                        }
                        else if (aiR == 2)
                        {
                            x.LouJianOrGuopan = louWu(
                              noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                              noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1]
                              );
                        }
                        else if (aiR == 3)
                        {
                            x.LouJianOrGuopan = louWu(
                              noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                                 noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[2],
                              noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1],
                                   noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[2]
                              );
                        }
                    }

                    List<string> aielInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.ElAiDetectInfo))
                    {
                        string[] allQx = x.ElAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aielInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aielInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aielInfoList = aielInfoList.Distinct().ToList();
                    aielInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ElAiDetectInfo = string.Join(",", aielInfoList);

                    List<string> aiviInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.ViAiDetectInfo))
                    {
                        string[] allQx = x.ViAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aiviInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aiviInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aiviInfoList = aiviInfoList.Distinct().ToList();
                    aiviInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ViAiDetectInfo = string.Join(",", aiviInfoList);

                    List<string> aivbInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.VBAiDetectInfo))
                    {
                        string[] allQx = x.VBAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aivbInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aivbInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aivbInfoList = aivbInfoList.Distinct().ToList();
                    aivbInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.VBAiDetectInfo = string.Join(",", aivbInfoList);

                });

                lsresult.ForEach(x => {
                    if (x.HumanJudgeTime != TimeSpan.Zero && string.IsNullOrWhiteSpace(x.LouJianOrGuopan))
                    {
                        x.LouJianOrGuopan = "NG";
                    }

                });

                // 针对 lsresult处理
                var reportDefectData = AiDefectStaticRRR.GetHReportDataHuman(lsresult);
                string addSettingAddress = string.Empty;
                if (AddressCombo.SelectedItem is KeyValuePair<string, string> kvp)
                {
                    // 是 key-value 对象
                    addSettingAddress = kvp.Key;

                }
                else
                {
                    addSettingAddress = AddressCombo.SelectedItem?.ToString()?.Split(',')[0];
                }
                if (typeExport.Equals("CSV", StringComparison.OrdinalIgnoreCase))
                {
                    string fileName = $@"{path}\{addSettingAddress}缺陷汇总误检信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
                    ReportExport<AiDefectStaticColumnHumanC>.ExportCsv(reportDefectData, fileName);
                    MessageBox.Show("导出结束");
                }
                else
                {
                    string fileName = $@"{path}\{addSettingAddress}缺陷汇总误检信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
                    ReportExport<AiDefectStaticColumnHumanC>.ExportXsls(reportDefectData, fileName);
                    MessageBox.Show("导出结束");
                }

            }
            catch (Exception ed)
            {
                SoftCommon.Log.Write("导出异常：" + ed.Message);
                MessageBox.Show("导出异常！！");

            }
            #region btn
            aiDefectNofoundBtn.IsEnabled = true;

            #endregion
        }

        private void databaseTest_Click(object sender, RoutedEventArgs e)
        {
            #region btn
            databaseTest.IsEnabled = false;
            #endregion
                       

            WhereQ whereQ = new WhereQ();
            //whereQ.Date = reportDate.SelectedDate??DateTime.MinValue;
            whereQ.BeginTime = beginDate.TimeValue;
            whereQ.EndTime = endDate.TimeValue;
            // whereQ.EquitepmentId = EquipmentCombo.SelectedValue?.ToString();
            var selectEquips = EquipmentCombo.SelectedItems.Cast<string>().ToList();
            whereQ.ManyEquitepmentIds = selectEquips;

            string address = AddressCombo.SelectedValue?.ToString();
            string typeExport = exportType.SelectedValue?.ToString();
            var hasconect = SqlTestHelper.HasConnected(address);
            SoftCommon.Log.Write("连接情况：" + hasconect);
            if (hasconect)
            {
                MessageBox.Show("测试连接成功！");
            }
            else
            {
                MessageBox.Show("测试连接异常，请检查数据库连接和确认数据库是否正常！");
            }
            databaseTest.IsEnabled = true;


        }

        private void dataTest_Click(object sender, RoutedEventArgs e)
        {
            #region btn
            dataTest.IsEnabled = false;
            #endregion


            WhereQ whereQ = new WhereQ();
            //whereQ.Date = reportDate.SelectedDate??DateTime.MinValue;
            whereQ.BeginTime = beginDate.TimeValue;
            whereQ.EndTime = endDate.TimeValue;
            // whereQ.EquitepmentId = EquipmentCombo.SelectedValue?.ToString();
            var selectEquips = EquipmentCombo.SelectedItems.Cast<string>().ToList();
            whereQ.ManyEquitepmentIds = selectEquips;

            string address = AddressCombo.SelectedValue?.ToString();
            string typeExport = exportType.SelectedValue?.ToString();
            var hasdata  = SqlTestHelper.HasNumberData(whereQ, address);
            SoftCommon.Log.Write("该数据库该时间段有数据条数：" + hasdata);
            if (hasdata > 0)
            {
                MessageBox.Show($"该数据库该时间段有数据{hasdata}数！");
            }
            else
            {
                MessageBox.Show($"该数据库该时间段不存在数据，请确认一人多机是否正常插入数据表！");
            }
            


            dataTest.IsEnabled = true;
            
        }



        void CommonRate()
        {
        
        }

        private void dataTotalRateBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region btn
                dataTotalRateBtn.IsEnabled = false;
                #endregion

                SoftCommon.Log.Write($"dataTotalRateBtn_Click");
                string path = string.Empty;
                // 创建 FolderBrowserDialog 对话框实例
                using (System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    // 显示对话框，并等待用户选择文件夹
                    System.Windows.Forms.DialogResult result = folderDialog.ShowDialog();

                    // 如果用户点击了确定按钮，获取选定的文件夹路径并显示在界面上
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        path = folderDialog.SelectedPath;
                    }
                }
                SoftCommon.Log.Write($"用户选择文件保存地址：{path}");
                if (string.IsNullOrWhiteSpace(path))
                {
                    #region btn
                    aiDefectBaseBtn.IsEnabled = true;

                    #endregion
                    return;
                }

                WhereQ whereQ = new WhereQ();
                //whereQ.Date = reportDate.SelectedDate??DateTime.MinValue;
                whereQ.BeginTime = beginDate.TimeValue;
                whereQ.EndTime = endDate.TimeValue;
                // whereQ.EquitepmentId = EquipmentCombo.SelectedValue?.ToString();
                var selectEquips = EquipmentCombo.SelectedItems.Cast<string>().ToList();
                whereQ.ManyEquitepmentIds = selectEquips;

                string address = AddressCombo.SelectedValue?.ToString();
                string typeExport = exportType.SelectedValue?.ToString();

                //finishtime -- judge
                var dstail = ReportHelper.GetColRowReportInfo(whereQ, address);
                var dtval = ReportHelper.DetailReportTrans(dstail.Tables[0]);
                var lsresult = ReportHelper.DicColRowToList(dtval);

                lsresult.ForEach(x =>
                {
                    // var min = FindMinTime(x.ElCreateTime,x.VICreateTime,x.VBCreateTime);
                    var min_max = FindMaxTime(x.ElCreateTime, x.VICreateTime, x.VBCreateTime);
                    var max = FindMaxTime(x.ElFinishTime, x.VIFinishTime, x.VBFinishTime);
                    if (min_max == DateTime.MinValue || max == DateTime.MinValue)
                    {

                    }
                    else
                    {
                        x.HumanJudgeTime = max - min_max;
                    }
                    var direc = isDirectRes(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    x.IsDirect = direc ? "是" : "否";
                    if (direc)
                    {
                        x.HumanJudgeTime = TimeSpan.Zero;
                    }
                    int aiR = noNullResult(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    int RenR = noNullResult(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult);
                    if (aiR == RenR)
                    {
                        if (aiR == 1)
                        {
                            x.LouJianOrGuopan = louWu(
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0]
                                );
                        }
                        else if (aiR == 2)
                        {
                            x.LouJianOrGuopan = louWu(
                              noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                              noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1]
                              );
                        }
                        else if (aiR == 3)
                        {
                            x.LouJianOrGuopan = louWu(
                              noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                                 noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[2],
                              noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1],
                                   noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[2]
                              );
                        }
                    }

                    List<string> aielInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.ElAiDetectInfo))
                    {
                        string[] allQx = x.ElAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aielInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aielInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aielInfoList = aielInfoList.Distinct().ToList();
                    aielInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ElAiDetectInfo = string.Join(",", aielInfoList);

                    List<string> aiviInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.ViAiDetectInfo))
                    {
                        string[] allQx = x.ViAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aiviInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aiviInfoList.Add(shuzu[1]);
                            }

                        }
                    }
                    aiviInfoList = aiviInfoList.Distinct().ToList();
                    aiviInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ViAiDetectInfo = string.Join(",", aiviInfoList);

                    List<string> aivbInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.VBAiDetectInfo))
                    {
                        string[] allQx = x.VBAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aivbInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aivbInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aivbInfoList = aivbInfoList.Distinct().ToList();
                    aivbInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.VBAiDetectInfo = string.Join(",", aivbInfoList);

                });
                SoftCommon.Log.Write("lsresult.ForEach");
                lsresult.ForEach(x => {
                    if (x.HumanJudgeTime != TimeSpan.Zero && string.IsNullOrWhiteSpace(x.LouJianOrGuopan))
                    {
                        x.LouJianOrGuopan = "NG";
                    }

                });
                SoftCommon.Log.Write("11111111");
                // 针对 lsresult处理
                var totalNum =lsresult.Count();
                var zhitong = lsresult.Count(x => x.HumanJudgeTime!=null&& x.HumanJudgeTime == TimeSpan.Zero);
                var wupan = lsresult.Count(x => !string.IsNullOrWhiteSpace(x.LouJianOrGuopan) && x.LouJianOrGuopan.Equals("过判"));     
                var ng =lsresult.Count(x =>!string.IsNullOrWhiteSpace(x.LouJianOrGuopan)&& x.LouJianOrGuopan.Equals("NG"));
                SoftCommon.Log.Write("12121212：" + zhitong+"0"+ totalNum+"0"+ wupan+"0"+ ng);
                DataStaticsRate dataStaticsRate = new DataStaticsRate()
                {
                    DirectRate = totalNum == 0 ? 0 : Math.Round((decimal)zhitong / totalNum, 4),
                    TotalFaultRate = totalNum == 0 ? 0 : Math.Round((decimal)wupan / totalNum, 4),
                    ProductNumber = totalNum,
                     AiNG = totalNum-zhitong,
                      HumanNG = ng
                };
                SoftCommon.Log.Write("22222222："  + "0" + totalNum + "0" + wupan + "0" + ng);
                string addSettingAddress = string.Empty;
                if (AddressCombo.SelectedItem is KeyValuePair<string, string> kvp)
                {
                    // 是 key-value 对象
                    addSettingAddress = kvp.Key;

                }
                else
                {
                    addSettingAddress = AddressCombo.SelectedItem?.ToString()?.Split(',')[0];
                }
                if (typeExport.Equals("CSV", StringComparison.OrdinalIgnoreCase))
                {
                    string fileName = $@"{path}\{addSettingAddress}总比率信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
                    ReportExport<DataStaticsRate>.ExportCsv(new List<DataStaticsRate>() { dataStaticsRate }, fileName);
                    MessageBox.Show("导出结束");
                }
                else
                {
                    string fileName = $@"{path}\{addSettingAddress}总比率信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
                    ReportExport<DataStaticsRate>.ExportXsls(new List<DataStaticsRate>() { dataStaticsRate }, fileName);
                    MessageBox.Show("导出结束");
                }

            }
            catch (Exception ed)
            {
                SoftCommon.Log.Write("导出异常：" + ed.Message);
                MessageBox.Show("导出异常！！");

            }
            #region btn
            dataTotalRateBtn.IsEnabled = true;

            #endregion
        }

        private void defectRateBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region btn
                defectRateBtn.IsEnabled = false;
                #endregion

                SoftCommon.Log.Write($"defectRateBtn_Click");
                string path = string.Empty;
                // 创建 FolderBrowserDialog 对话框实例
                using (System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    // 显示对话框，并等待用户选择文件夹
                    System.Windows.Forms.DialogResult result = folderDialog.ShowDialog();

                    // 如果用户点击了确定按钮，获取选定的文件夹路径并显示在界面上
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        path = folderDialog.SelectedPath;
                    }
                }
                SoftCommon.Log.Write($"用户选择文件保存地址：{path}");
                if (string.IsNullOrWhiteSpace(path))
                {
                    #region btn
                    aiDefectBaseBtn.IsEnabled = true;

                    #endregion
                    return;
                }

                WhereQ whereQ = new WhereQ();
                //whereQ.Date = reportDate.SelectedDate??DateTime.MinValue;
                whereQ.BeginTime = beginDate.TimeValue;
                whereQ.EndTime = endDate.TimeValue;
                // whereQ.EquitepmentId = EquipmentCombo.SelectedValue?.ToString();
                var selectEquips = EquipmentCombo.SelectedItems.Cast<string>().ToList();
                whereQ.ManyEquitepmentIds = selectEquips;

                string address = AddressCombo.SelectedValue?.ToString();
                string typeExport = exportType.SelectedValue?.ToString();

                //finishtime -- judge
                var dstail = ReportHelper.GetColRowReportInfo(whereQ, address);
                var dtval = ReportHelper.DetailReportTrans(dstail.Tables[0]);
                var lsresult = ReportHelper.DicColRowToList(dtval);
                lsresult.ForEach(x =>
                {
                    // var min = FindMinTime(x.ElCreateTime,x.VICreateTime,x.VBCreateTime);
                    var min_max = FindMaxTime(x.ElCreateTime, x.VICreateTime, x.VBCreateTime);
                    var max = FindMaxTime(x.ElFinishTime, x.VIFinishTime, x.VBFinishTime);
                    if (min_max == DateTime.MinValue || max == DateTime.MinValue)
                    {

                    }
                    else
                    {
                        x.HumanJudgeTime = max - min_max;
                    }
                    var direc = isDirectRes(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    x.IsDirect = direc ? "是" : "否";
                    if (direc)
                    {
                        x.HumanJudgeTime = TimeSpan.Zero;
                    }
                    int aiR = noNullResult(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    int RenR = noNullResult(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult);
                    if (aiR == RenR)
                    {
                        if (aiR == 1)
                        {
                            x.LouJianOrGuopan = louWu(
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0]
                                );
                        }
                        else if (aiR == 2)
                        {
                            x.LouJianOrGuopan = louWu(
                              noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                              noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1]
                              );
                        }
                        else if (aiR == 3)
                        {
                            x.LouJianOrGuopan = louWu(
                              noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                                 noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[2],
                              noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1],
                                   noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[2]
                              );
                        }
                    }

                    List<string> aielInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.ElAiDetectInfo))
                    {
                        string[] allQx = x.ElAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aielInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aielInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aielInfoList = aielInfoList.Distinct().ToList();
                    aielInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ElAiDetectInfo = string.Join(",", aielInfoList);

                    List<string> aiviInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.ViAiDetectInfo))
                    {
                        string[] allQx = x.ViAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aiviInfoList.Add(shuzu[1]);
                            }
                            else if(shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aiviInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aiviInfoList = aiviInfoList.Distinct().ToList();
                    aiviInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ViAiDetectInfo = string.Join(",", aiviInfoList);

                    List<string> aivbInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.VBAiDetectInfo))
                    {
                        string[] allQx = x.VBAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aivbInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aivbInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aivbInfoList = aivbInfoList.Distinct().ToList();
                    aivbInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.VBAiDetectInfo = string.Join(",", aivbInfoList);

                });

                lsresult.ForEach(x => {
                    if (x.HumanJudgeTime != TimeSpan.Zero && string.IsNullOrWhiteSpace(x.LouJianOrGuopan))
                    {
                        x.LouJianOrGuopan = "NG";
                    }

                });

                // 针对 lsresult处理
                var reportDefectData = AiDefectStaticRRR.GetHReportDataAi11111(lsresult);
                var totalDefectNumber = reportDefectData.Sum(x => x.DefectCount);
                List<DefectRateStaticColumn>defectRateStaticColumns = new List<DefectRateStaticColumn>();
                foreach (var item in reportDefectData)
                {
                    DefectRateStaticColumn defectRateStatic = new DefectRateStaticColumn()
                    {
                        DefectCount = item.DefectCount,
                        DefectName = item.DefectName,
                        DefectRate = totalDefectNumber == 0 ? 0 : Math.Round((decimal)item.DefectCount/totalDefectNumber,4)
                    };
                    defectRateStaticColumns.Add(defectRateStatic);
                }

                string addSettingAddress = string.Empty;
                if (AddressCombo.SelectedItem is KeyValuePair<string, string> kvp)
                {
                    // 是 key-value 对象
                    addSettingAddress = kvp.Key;

                }
                else
                {
                    addSettingAddress = AddressCombo.SelectedItem?.ToString()?.Split(',')[0];
                }
                if (typeExport.Equals("CSV", StringComparison.OrdinalIgnoreCase))
                {
                    string fileName = $@"{path}\{addSettingAddress}缺陷比率信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
                    ReportExport<DefectRateStaticColumn>.ExportCsv(defectRateStaticColumns, fileName);
                    MessageBox.Show("导出结束");
                }
                else
                {
                    string fileName = $@"{path}\{addSettingAddress}缺陷比率信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
                    ReportExport<DefectRateStaticColumn>.ExportXsls(defectRateStaticColumns, fileName);
                    MessageBox.Show("导出结束");
                }

            }
            catch (Exception ed)
            {
                SoftCommon.Log.Write("导出异常：" + ed.Message);
                MessageBox.Show("导出异常！！");

            }
            #region btn
            defectRateBtn.IsEnabled = true;

            #endregion
        }

        private void imgClaBtn_Click(object sender, RoutedEventArgs e)
        {
            WhereQ whereQ = new WhereQ();
            //whereQ.Date = reportDate.SelectedDate??DateTime.MinValue;
            whereQ.BeginTime = beginDate.TimeValue;
            whereQ.EndTime = endDate.TimeValue;
            // whereQ.EquitepmentId = EquipmentCombo.SelectedValue?.ToString();
            var selectEquips = EquipmentCombo.SelectedItems.Cast<string>().ToList();
            whereQ.ManyEquitepmentIds = selectEquips;

            string address = AddressCombo.SelectedValue?.ToString();   

            PictureClassifyWindow pictureClassifyWindow = new PictureClassifyWindow();
            pictureClassifyWindow.GetWhereQ = whereQ;
            pictureClassifyWindow.Address = address;
            pictureClassifyWindow.ShowDialog();
        }

        private void dataFanXiuBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region btn
                dataFanXiuBtn.IsEnabled = false;
                #endregion

                SoftCommon.Log.Write($"colRowReportBtn_Click");
                string path = string.Empty;
                // 创建 FolderBrowserDialog 对话框实例
                using (System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    // 显示对话框，并等待用户选择文件夹
                    System.Windows.Forms.DialogResult result = folderDialog.ShowDialog();

                    // 如果用户点击了确定按钮，获取选定的文件夹路径并显示在界面上
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        path = folderDialog.SelectedPath;
                    }
                }
                SoftCommon.Log.Write($"用户选择文件保存地址：{path}");
                if (string.IsNullOrWhiteSpace(path))
                {
                    #region btn
                    dataFanXiuBtn.IsEnabled = true;

                    #endregion
                    return;
                }

                WhereQ whereQ = new WhereQ();
                //whereQ.Date = reportDate.SelectedDate??DateTime.MinValue;
                whereQ.BeginTime = beginDate.TimeValue;
                whereQ.EndTime = endDate.TimeValue;
                // whereQ.EquitepmentId = EquipmentCombo.SelectedValue?.ToString();
                var selectEquips = EquipmentCombo.SelectedItems.Cast<string>().ToList();
                whereQ.ManyEquitepmentIds = selectEquips;

                string address = AddressCombo.SelectedValue?.ToString();
                string typeExport = exportType.SelectedValue?.ToString();

                //finishtime -- judge
                var dstail = ReportHelper.GetColRowReportInfo(whereQ, address);
                var dtval = ReportHelper.DetailReportTrans(dstail.Tables[0]);
                var lsresult = FanXiuReportHelper.DicToFanXiuList(dtval);
                lsresult = lsresult.Where(x => x.Checked > 0).ToList();
                lsresult.ForEach(x =>
                {
                    // var min = FindMinTime(x.ElCreateTime,x.VICreateTime,x.VBCreateTime);
                    var min_max = FindMaxTime(x.ElCreateTime, x.VICreateTime, x.VBCreateTime);
                    var max = FindMaxTime(x.ElFinishTime, x.VIFinishTime, x.VBFinishTime);
                    if (min_max == DateTime.MinValue || max == DateTime.MinValue)
                    {

                    }
                    else
                    {
                        x.HumanJudgeTime = max - min_max;
                    }
                    var direc = isDirectRes(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    x.IsDirect = direc ? "是" : "否";
                    if (direc)
                    {
                        x.HumanJudgeTime = TimeSpan.Zero;
                    }
                    int aiR = noNullResult(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    int RenR = noNullResult(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult);
                    if (aiR == RenR)
                    {
                        if (aiR == 1)
                        {
                            x.LouJianOrGuopan = louWu(
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0]
                                );
                        }
                        else if (aiR == 2)
                        {
                            x.LouJianOrGuopan = louWu(
                              noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                              noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1]
                              );
                        }
                        else if (aiR == 3)
                        {
                            x.LouJianOrGuopan = louWu(
                              noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                                 noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[2],
                              noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1],
                                   noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[2]
                              );
                        }
                    }

                    List<string> aielInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.ElAiDetectInfo))
                    {
                        string[] allQx = x.ElAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aielInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aielInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aielInfoList = aielInfoList.Distinct().ToList();
                    aielInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ElAiDetectInfo = string.Join(",", aielInfoList);

                    List<string> aiviInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.ViAiDetectInfo))
                    {
                        string[] allQx = x.ViAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aiviInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aiviInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aiviInfoList = aiviInfoList.Distinct().ToList();
                    aiviInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ViAiDetectInfo = string.Join(",", aiviInfoList);

                    List<string> aivbInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.VBAiDetectInfo))
                    {
                        string[] allQx = x.VBAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aivbInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aivbInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aivbInfoList = aivbInfoList.Distinct().ToList();
                    aivbInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.VBAiDetectInfo = string.Join(",", aivbInfoList);

                });

                lsresult.ForEach(x => {
                    if (x.HumanJudgeTime != TimeSpan.Zero && string.IsNullOrWhiteSpace(x.LouJianOrGuopan))
                    {
                        x.LouJianOrGuopan = "NG";
                    }

                });
                string addSettingAddress = string.Empty;
                if (AddressCombo.SelectedItem is KeyValuePair<string, string> kvp)
                {
                    // 是 key-value 对象
                    addSettingAddress = kvp.Key;

                }
                else
                {
                    addSettingAddress = AddressCombo.SelectedItem?.ToString()?.Split(',')[0];
                }
                if (typeExport.Equals("CSV", StringComparison.OrdinalIgnoreCase))
                {
                    string fileName = $@"{path}\{addSettingAddress}回流信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
                    ReportExport<FanXiuColRowReport>.ExportCsv(lsresult, fileName);
                    MessageBox.Show("导出结束");
                }
                else
                {
                    string fileName = $@"{path}\{addSettingAddress}回流信息报表_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
                    ReportExport<FanXiuColRowReport>.ExportXsls(lsresult, fileName);
                    MessageBox.Show("导出结束");
                }

            }
            catch (Exception ed)
            {
                SoftCommon.Log.Write("导出异常：" + ed.Message);
                MessageBox.Show("导出异常！！");

            }
            #region btn
            dataFanXiuBtn.IsEnabled = true;

            #endregion
        }

        private void fanxiuDataTest_Click(object sender, RoutedEventArgs e)
        {
            #region btn
            fanxiuDataTest.IsEnabled = false;
            #endregion


            WhereQ whereQ = new WhereQ();
            //whereQ.Date = reportDate.SelectedDate??DateTime.MinValue;
            whereQ.BeginTime = beginDate.TimeValue;
            whereQ.EndTime = endDate.TimeValue;
            // whereQ.EquitepmentId = EquipmentCombo.SelectedValue?.ToString();
            var selectEquips = EquipmentCombo.SelectedItems.Cast<string>().ToList();
            whereQ.ManyEquitepmentIds = selectEquips;

            string address = AddressCombo.SelectedValue?.ToString();
            string typeExport = exportType.SelectedValue?.ToString();
            var hasdata = SqlTestHelper.HasFanXiuNumberData(whereQ, address);
            SoftCommon.Log.Write("该数据库该时间段有返修数据条数：" + hasdata);
            if (hasdata > 0)
            {
                MessageBox.Show($"该数据库该时间段有返修数据{hasdata}数！");
            }
            else
            {
                MessageBox.Show($"该数据库该时间段不存在返修数据，请确认一人多机是否正常记录返修数据信息！");
            }



            fanxiuDataTest.IsEnabled = true;
        }
    }
}
